import datetime
import string
import time
import random

from iotdb.Session import Session

from dao.time import creatData
from utils.config import Config
from utils.logger import Logger

logger = Logger('Iot').getlogger()


class Iot():
    def __init__(self):
        self.config = Config('./conf/config.ini')
        self.ip = self.config.read_value('iot', 'ip')
        self.port_ = self.config.read_value('iot', 'port')
        self.username_ = self.config.read_value('iot', 'username')
        self.password_ = self.config.read_value('iot', 'password')
        self.session = None  # 初始化session变量

    # 创建一个与IoTDB服务器的会话
    def comm(self):
        retry_count = 3
        retry_delay = 2  # 秒
        
        for attempt in range(retry_count):
            try:
                if self.session is None:
                    self.session = Session(self.ip, self.port_, self.username_, self.password_)
                    self.session.open(False)
                    return self.session
            except Exception as e:
                if attempt < retry_count - 1:
                    logger.warning(f"连接尝试 {attempt + 1} 失败: {str(e)}，{retry_delay}秒后重试...")
                    time.sleep(retry_delay)
                else:
                    logger.error(f"连接失败，已重试{retry_count}次: {str(e)}")
                    raise
        return self.session

    # 执行查询语句
    def search(self,query):
        session = self.comm()
        result = session.execute_query_statement(query)
        df=result.todf()
        return df

    # 执行非查询语句
    def non_search(self,query):
        session = self.comm()
        result =session.execute_non_query_statement(query)
        return result


# iot=Iot()
# #雨水泵
# sql='select ZERO_DURATION(Stop) as a from root.iotdata.L39t5xtgx.K_YSB5_D3 where time>=2024-07-27T00:00:00.000+08:00 and time<=2024-07-30T00:00:00.000+08:00;'
# #废水泵
# # sql='select ZERO_DURATION(Stop) as a from root.iotdata.b3Qm59mg9.K_JZFSBn1 where time>=2024-07-27T00:00:00.000+08:00 and time<=2024-07-30T00:00:00.000+08:00;'
# result=iot.search(sql)
# df=result.todf()
# print(df)
#
# time.sleep(1)
# df1=sum(df.a)/60000
# print(df1)


# iot=Iot()
# # 构造江阴隧道左洞passiofo数据
# def create_passinfo(location,num,timestamp=None):
#     sql_statements = []
#     id=123+num
#     current_timestamp = int(time.time()*1000)
#     objectClass=random.randint(1, 10)
#     num=random.randint(45000, 145000)
#     color=random.randint(1, 7)
#     if location=="jyright":
#         lane=random.randint(1, 3)
#     else:
#         lane=random.randint(4, 6)
#     plate="湘" + random.choice(string.ascii_uppercase[:8]) +''.join(random.choices(string.ascii_uppercase + string.digits, k=5))
#
#     if timestamp==None:
#         sql=f'INSERT INTO root.jingjiang.passinfo.{location}(id,objectClass,lane,plate,stakeMark,counter,enterTime,outTime,avgSpeed,passTime,plateColor,outStakeMark,color) VALUES({id},{objectClass},{lane},\'{plate}\',"LK2+100",1,{current_timestamp},{current_timestamp+num},63.2,{num},{color},"LK5+370",{color})'
#     else:
#         sql=f'INSERT INTO root.jingjiang.passinfo.{location}(time,id,objectClass,lane,plate,stakeMark,counter,enterTime,outTime,avgSpeed,passTime,plateColor,outStakeMark,color) VALUES({timestamp},{id},{objectClass},{lane},\'{plate}\',"LK2+100",1,{current_timestamp},{current_timestamp+num},63.2,{num},{color},"LK5+370",{color})'
#     sql_statements.append(sql)
#     return sql_statements
#
# for i in range(29):
#     # num = random.randint(1, 23)
#     # num2=random.randint(10, 59)
#     # num3=random.randint(10, 59)
#     # timestamp_ms=creatData(f'2024-09-05 {num}:{num2}:{num3}')
#     sql_statements = create_passinfo('jyright',num=i)   # , timestamp=timestamp_ms
#     for sql in sql_statements:
#         iot.non_search(sql)
#         time.sleep(0.5)

# 造数据用于测试
# import random
# from datetime import datetime
#
# start_date = int(datetime(2025, 1, 1, 0, 0, 0).timestamp() * 1000)
# end_date = int(datetime(2025, 1, 2, 0, 0, 0).timestamp() * 1000)
#
# sql_statements = []
#
# current_time = start_date
# while current_time <= end_date:
#     # 生成随机值
#     power_switch = 0 if random.random() < 0.8 else 1  # 80%概率为0
#     target_temperature = random.randint(20, 35)  # 随机的 TargetTemperature 值
#
#     # 构建 SQL 语句   k3FrgbrDb   N3LwiSw4S
#     sql = f"INSERT INTO root.iotdata.u3bVeqVQq.k3FrgbrDb(timestamp,PowerSwitch,ct,nt,v,TargetTemperature) VALUES ({current_time}, {power_switch}, 1714276468191, 1714276466959, 1, {target_temperature})"
#
#     # 添加到列表
#     sql_statements.append(sql)
#
#     # 增加10秒
#     current_time +=20000
# iot=Iot()
# for sql in sql_statements:
#     iot.non_search(sql)
#     time.sleep(0.1)